package com.sprite.framework.entity.mapper.reolver.node;

import java.util.List;
import java.util.Map;

import com.sprite.framework.entity.mapper.reolver.DynamicContext;
import com.sprite.framework.entity.mapper.reolver.SqlNode;
import com.sprite.utils.UtilString;

/**
 * trim、set、where
 * @author Jack
 *
 */
public class TrimSqlNode implements SqlNode{
	private String prefix;
	private String prefixOverride;
	private String suffix;
	private String suffixOverride;

	private SqlNode content;

	public boolean apply(DynamicContext context) {

		DynamicContextProxy proxy = new DynamicContextProxy(context);
		boolean isApply = this.content.apply(proxy);
		if(!isApply){
			return false;
		}
		
		context.append(prefix);
		String sql = proxy.toSql().trim();

		if(prefixOverride != null){
			List<String> list = UtilString.tokenizeToStringList(prefixOverride, "|");

			for(String override : list){
				override = override.trim();

				if(sql.startsWith(override)){
					sql = sql.substring(override.length()).trim();
				}
			}
		}


		if(suffixOverride != null){
			List<String> list = UtilString.tokenizeToStringList(suffixOverride, "|");

			for(String override : list){
				override = override.trim();
				if(sql.endsWith(override)){
					sql = sql.substring(0, sql.length() - override.length()).trim();
				}
			}
		}


		context.append(sql);
		context.addParams(proxy.getParams());

		if(isApply){
			context.append(suffix);
		}
		return false;
	}

	public String getPrefix() {
		return prefix;
	}

	public void setPrefix(String prefix) {
		this.prefix = prefix;
	}

	public String getPrefixOverride() {
		return prefixOverride;
	}

	public void setPrefixOverride(String prefixOverride) {
		this.prefixOverride = prefixOverride;
	}

	public String getSuffix() {
		return suffix;
	}

	public void setSuffix(String suffix) {
		this.suffix = suffix;
	}

	public String getSuffixOverride() {
		return suffixOverride;
	}

	public void setSuffixOverride(String suffixOverride) {
		this.suffixOverride = suffixOverride;
	}

	public SqlNode getContent() {
		return content;
	}

	public void setContent(SqlNode content) {
		this.content = content;
	}

	static class DynamicContextProxy extends DynamicContext{
		private DynamicContext orginal;

		public DynamicContextProxy(DynamicContext context) {
			super(null);
			orginal = context;
			setNamespace(context.getNamespace());
		}

		public Map<String, Object> getBindings(){
			return orginal.getBindings();
		}

		public void bind(String key, Object value){
			orginal.bind(key, value);
		}
	}

}
